layui.use(['form'],function() {
    var form = layui.form,
        $ = layui.jquery;

    // 使用延时，防止取不到隐藏域里的userId
    setTimeout(function () {
        $.ajax({
            url: '/role/listByUserId',
            dataType: 'json',
            data: {userId:$(".userId").val()},
            success: function(res){
                if(res != null){
                    $.each(res, function (index, item) {
                        if (item.checked == true) {
                            $(".roleList").append('<input type="checkbox" id="' + item.id + '" name="roleId" value="' + item.id + '" title="' + item.roleName + '" checked><div class="layui-unselect layui-form-checkbox layui-form-checked"><span>' + item.roleName + '</span><i class="layui-icon layui-icon-ok"></i></div>');
                        } else {
                            $(".roleList").append('<input type="checkbox" id="' + item.id + '" name="roleId" value="' + item.id + '" title="' + item.roleName + '"><div class="layui-unselect layui-form-checkbox"><span>' + item.roleName + '</span><i class="layui-icon layui-icon-ok"></i></div>');
                        }
                    });
                }
                form.render();
            }
        });
    }, 80);

    form.on('submit(*)', function(data){
        var roleIds = [];
        $("input:checkbox[name='roleId']:checked").each(function() { // 遍历name=standard的多选框
            roleIds.push($(this).val());
        });

        $.ajax({
            url: '/role/updateUserRole',
            dataType: 'json',
            data: {
                userId:$(".userId").val(),
                roleIds:roleIds
            },
            success: function(res){
                if(res.status == 200){
                    var index=parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                }
            }
        });
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

    // 取消按钮
    $(".cancel_btn").click(function(){
        var index=parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    });
})